// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Y [author] rhyme_lph
// n [email]  rhymelph@gmail.com
// t [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/dashboard_leave_entity.dart';
import 'package:finance_app/src/entities/leave_item_entity.dart';
import 'package:finance_app/src/entities/leave_item_value.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/widgets/list_item/list_expandable_item.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/common/normal_table.dart';
import 'package:finance_app/src/widgets/dash_board/transaction_record_title_item.dart';
import 'package:finance_app/src/widgets/form/down_button_form.dart';
import 'package:finance_app/src/widgets/list_item/leaver_item.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/hr_payroll/views/leave_provider.dart';
import 'package:finance_app/src/provider/hr_payroll/hr_and_payroll_provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tuple/tuple.dart';

class LeaveView extends StatefulWidget {
  @override
  _LeaveViewState createState() => _LeaveViewState();
}

class _LeaveViewState extends State<LeaveView>
    with
        StatefulPresenter<LeaveView, HrAndPayrollProvider, LeaveProvider>,
        KeepAliveMixin {
  @override
  Widget buildEmptyWidget(BaseProvider _, BuildContext context) {
    return ColoredBox(
      color: Colors.white,
      child: SmartRefresher(
        controller: provider.refreshController,
        onRefresh: provider.onRefresh,
        onLoading: provider.onLoadMore,
        enablePullUp: false,
        child: Column(
          children: [
            if (Config.hasPermission(PermissionUtils.hrPayroll)) AppSpaces.h20,
            if (Config.hasPermission(PermissionUtils.hrPayroll))
              listBuilder<String>(
                selector: (_, __) => __.currentSelectEmployee?.name,
                builder: (BuildContext context, String value, Widget child) =>
                    DownButtonForm(
                  title: value ?? S.current.all,
                  onTap: provider.onChangeEmployee,
                ),
              ),
            AppSpaces.h25,
            ListHeaderItem(
              title: S.current.leave_overview,
            ),
            listBuilder<List<DashboardLeaveEntity>>(
              selector: (_, __) => List.from(__.data),
              builder: (BuildContext context, List<DashboardLeaveEntity> value,
                      Widget child) =>
                  NormalTable(
                header: TableItem(
                    S.current.leave, S.current.used, S.current.balance),
                items: value
                    .map((e) => TableItem(
                        e.name,
                        '${e.used ~/ 1}/${e.total ~/ 1}',
                        '${(e.total - e.used) ~/ 1}'))
                    .toList(),
              ),
            ),
            ListHeaderItem(
              title: S.current.leave_details,
            ),
            AppSpaces.h10,
            Expanded(child: super.buildEmptyWidget(_, context))
          ],
        ),
      ),
    );
  }

  @override
  Widget buildWidget(BuildContext context) => ColoredBox(
        color: Colors.white,
        child: SmartRefresher(
          controller: provider.refreshController,
          onRefresh: provider.onRefresh,
          onLoading: provider.onLoadMore,
          enablePullUp: false,
          child: ListView(
            controller: provider.controller,
            children: [
              if (Config.hasPermission(PermissionUtils.hrPayroll))
                AppSpaces.h20,
              if (Config.hasPermission(PermissionUtils.hrPayroll))
                listBuilder<String>(
                  selector: (_, __) => __.currentSelectEmployee?.name,
                  builder: (BuildContext context, String value, Widget child) =>
                      DownButtonForm(
                    title: value ?? S.current.all,
                    onTap: provider.onChangeEmployee,
                  ),
                ),
              AppSpaces.h25,
              ListHeaderItem(
                title: S.current.leave_overview,
              ),
              NormalTable(
                header: TableItem(
                    S.current.leave, S.current.used, S.current.balance),
                items: provider.data
                    .map((e) => TableItem(e.name.replaceAll('(Days)', ''),
                        '${e.used}/${e.total}', '${(e.total - e.used)}'))
                    .toList(),
              ),
              listBuilder<
                  Tuple3<String, List<LeaveItemEntity>, LeaveItemValue>>(
                selector: (_, __) => Tuple3(__.currentType,
                    List.from(__.dataList), __.leaveMap[__.currentType]),
                builder: (BuildContext context,
                    Tuple3<String, List<LeaveItemEntity>, LeaveItemValue> value,
                    Widget child) {
                  if (value.item1 == null) {
                    return Column(
                      children: provider.leaveMap.entries
                          .map((e) => ListExpandableItem(
                                controller: e.value.controller,
                                titleSpans: [
                                  TextSpan(text: provider.getGroupName(e.key)),
                                  if (e.key == 'pending')
                                    TextSpan(
                                        text:
                                            '(${(e.value.allData?.length ?? 0) > 10 ? '10+' : e.value.allData?.length ?? 0})',
                                        style: TextStyle(
                                          color: aceRedColor,
                                        ))
                                ],
                              ))
                          .toList(),
                    );
                  } else {
                    List<Widget> children = [];
                    for (final e in value.item3.groupMap.entries) {
                      children.add(TransactionRecordTitleItem(
                        topPadding: getDp(14),
                        title: e.key,
                      ));
                      children.add(AppSpaces.grayH05);
                      children.addAll(e.value.map(buildItemWidget).toList());
                    }
                    if (children.isEmpty) {
                      children.add(Padding(
                        padding: EdgeInsets.only(top: getDp(30)),
                        child: super.buildEmptyWidget(provider, context),
                      ));
                    }
                    return ListExpandableItem(
                      controller: value.item3.controller,
                      titleSpans: [
                        TextSpan(text: provider.getGroupName(value.item1)),
                        if (value.item1 == 'pending')
                          TextSpan(
                              text:
                                  '(${value.item3.allData.length > 10 ? '10+' : value.item3.allData.length})',
                              style: TextStyle(
                                color: aceRedColor,
                              ))
                      ],
                      content: Column(
                        children: children,
                      ),
                    );
                  }
                },
              ),
            ],
          ),
        ),
      );

  Widget buildItemWidget(LeaveItemEntity e) {
    return PressedOpacityButton(
      onPressed: () => provider.onNavDetail(e),
      child: LeaverItem(
        name: e.employeeName,
        title: e.leaveTypeName,
        timeRange:
            '${DateTimeUtils.formatDateTimeString(e.startDate)} ${e.startDateMeridian} - ${DateTimeUtils.formatDateTimeString(e.endDate)} ${e.endDateMeridian}',
        status: provider.getLeaveStatus(e),
        day: e.days,
      ),
    );
  }
}
